<template>
  <div>
    <!-- 头部 -->
    <div class="dark-top">
      <a @click="goback" class="page-back"><div></div></a>
      <div class="top-title">
        <div v-if="stuOrder.status">订单详情</div>
        <div v-else>等待付款</div>
        <!-- 倒计时 -->
        <div v-if="stuOrder.status" class="topTime"></div>
        <div v-else class="topTime">
          订单将在{{ minute }}:{{ second }}分钟后关闭
        </div>
      </div>
    </div>
    <!-- 与绝对定位的高度一样 -->
    <div style="height: 12.5rem;"></div>
    <!-- 订单信息 -->
    <div class="dark-order">
      <div class="dark-order-div1">
        <span>订单编号</span
        ><span class="order-span1">{{ stuOrder.number }}</span>
      </div>
      <div class="dark-order-div2">
        <span>创建时间</span
        ><span class="order-span2">{{ stuOrder.create_time }}</span>
      </div>
    </div>
    <!-- 与绝对定位的高度一样 -->
    <div style="height: 3.3125rem"></div>
    <!-- 订单详情列表 -->
    <div class="dark-order-list">
      <div class="order-list-box" v-for="item in myOrder" :key="item.id">
        <div class="box_left">
          <!-- 商品图 -->
          <div
            class="order-picture"
            :style="{ backgroundImage: 'url(' + item.picture + ')' }"
          ></div>
        </div>
        <!-- 商品内容 -->
        <div class="box_right">
          <div class="order-right-contend">
            {{ item.headline }}
          </div>
          <div class="order-right-gauge">规格：{{ item.gauge }}</div>
          <div class="order-right-price">￥{{ item.price }}</div>
        </div>
      </div>
    </div>
    <!-- 与绝对定位的高度一样 -->
    <div style="height: 2.8125rem;"></div>
    <!-- 底部	 -->
    <div class="dark-foot" v-if="stuOrder.status"></div>
    <div class="dark-foot" v-else>
      <div class="foot-left">
        <p>
          共{{ stuOrder.total }}件 合计：<span class="font-left-color">
            {{ stuOrder.total_mon }}元
          </span>
        </p>
        <p>
          实付：<span class="font-left-color">{{ stuOrder.real_pay }}元</span>
          <!-- 折扣：<span class="font-left-color">100元</span> -->
        </p>
      </div>
      <div class="foot-button" @click="wxpay">立即支付</div>
    </div>
  </div>
</template>
<script
  type="text/javascript"
  src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"
></script>
<script>
import { Indicator } from "mint-ui";
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      orderId: "",
      myOrder: [],
      stuOrder: [],
      code: "",
      url: "",
      minutes: 15,
      seconds: 0
    };
  },
  created() {
    this.orderId = this.$route.params.or_id;
    this.selMyOrderDetails();
    let me = this;
    if (location.href.indexOf("code=") === -1) {
    } else {
      me.wxpay();
    }
  },
  methods: {
    goback() {
      this.$router.go(-1);
    },
    num: function(n) {
      return n < 10 ? "0" + n : "" + n;
    },
    timeCountDown() {
      //倒计时
      var _this = this;
      var time = window.setInterval(function() {
        if (_this.seconds === 0 && _this.minutes !== 0) {
          _this.seconds = 59;
          _this.minutes -= 1;
        } else if (_this.minutes === 0 && _this.seconds === 0) {
          _this.seconds = 0;
          window.clearInterval(time);
        } else {
          _this.seconds -= 1;
        }
      }, 1000);
    },
    //详情页获取数据
    selMyOrderDetails() {
      if (this.orderId == null) {
        this.orderId = localStorage.or_id;
      }
      //console.log(this.orderId);
      //Indicator.open({ spinnerType: "fading-circle" });
      let me = this;
      this.$axios
        .post(
          "/api/home/myOrderDetails",
          { or_id: this.orderId },
          { emulateJSON: true }
        )
        .then(kun => {
          console.log(kun);
          //Indicator.close();
          if (kun.code == 200) {
            me.timeCountDown();
            me.myOrder = kun.data;
            me.stuOrder = kun.msg;
          } else if (kun.code == 600) {
            Toast(kun.msg);
            me.goback();
          } else {
            Toast(kun.msg);
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //订单支付成功 更新数据
    payOrderMoney() {
      let me = this;
      this.$axios
        .post(
          "/api/mall/payOrder",
          { oid: this.orderId, uid: localStorage.uid },
          { emulateJSON: true }
        )
        .then(kun => {
          console.log(kun);
          Indicator.close();
          if (kun.code == 200) {
            me.goback();
          } else {
            Toast(kun.msg);
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    // 截取code
    GetUrlParame(parameName) {
      /// 获取地址栏指定参数的值
      /// <param name="parameName">参数名</param>
      // 获取url中跟在问号后面的部分
      var parames = window.location.search;
      // 检测参数是否存在
      if (parames.indexOf(parameName) > -1) {
        var parameValue = "";
        parameValue = parames.substring(
          parames.indexOf(parameName),
          parames.length
        );
        // 检测后面是否还有参数
        if (parameValue.indexOf("&") > -1) {
          // 去除后面多余的参数, 得到最终 parameName=parameValue 形式的值
          parameValue = parameValue.substring(0, parameValue.indexOf("&"));
          // 去掉参数名, 得到最终纯值字符串
          parameValue = parameValue.replace(parameName + "=", "");
          return parameValue;
        }
        return "";
      }
    },
    wxpay() {
      //微信支付 获取code
      var href = location.href;
      if (href.indexOf("code=") === -1) {
        //如果没有code参数就直接调用授权函数
        this.get_weixin_code_login(); //调用授权函数
      } else {
        //如果有拿取code值
        this.getUrlCode();
        var local = window.location.href;
        console.log(local);
        this.code = this.GetUrlParame("code");
        if (this.code == null || this.code == "" || this.code == "undefined") {
          window.location.href = this.url;
        }
        this.getWxUserInfo(this.code);
      }
    },
    get_weixin_code_login() {
      var uri = window.location.href;
      var appid = "wx3de25cb8ef21fe75"; //自己公众号的appid
      var url =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        appid +
        "&redirect_uri=" +
        encodeURIComponent(uri) +
        "&response_type=code&scope=snsapi_userinfo&state=54321#wechat_redirect";
      window.location.href = url;
      this.url = url;
      // 这里走完就是已经授权了。如果授权了就会url中带有code
    },
    getUrlCode() {
      //获取url参数
      var url = location.search;
      this.winUrl = url;
      var theRequest = new Object();
      if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
        }
      }
      return theRequest;
    },
    getWxUserInfo(code) {
      //授权后获取用户的基本信息
      let me = this;
      console.log("授权码" + code);
      this.$axios
        .post(
          "/api/Wxpay/get_signature",
          { code: code, oid: this.orderId, uid: localStorage.uid },
          { emulateJSON: true }
        )
        .then(kun => {
          console.log("支付参数" + kun);

          if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
              document.addEventListener(
                "WeixinJSBridgeReady",
                me.onBridgeReady,
                false
              );
            } else if (document.attachEvent) {
              document.attachEvent("WeixinJSBridgeReady", me.onBridgeReady);
              document.attachEvent("onWeixinJSBridgeReady", me.onBridgeReady);
            }
          } else {
            //订单创建成功返回支付参数和order_id便于前端唤起支付
            console.log("唤起支付" + kun.appId);
            me.onBridgeReady(
              kun.appId,
              kun.timeStamp,
              kun.nonceStr,
              kun.package,
              kun.paySign,
              kun.signType,
              kun.order_id
            );
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    // 支付
    onBridgeReady(
      appid,
      time,
      nonceStr,
      prepay_id,
      paySign,
      trade_type,
      order_id
    ) {
      let me = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: appid, // 公众号名称，由商户传入
          timeStamp: time, // 时间戳，自1970年以来的秒数
          nonceStr: nonceStr, // 随机串
          package: prepay_id, // 统一下单接口返回的prepay_id参数值
          signType: trade_type, // 微信签名方式：
          paySign: paySign // 微信签名
        },
        function(res) {
          console.log(order_id);
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            Toast("支付成功");
            me.payOrderMoney();
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
            Toast("支付过程中用户取消");
          } else if (res.err_msg == "get_brand_wcpay_request:fail") {
            Toast("支付失败");
          } else {
            console.log(res);
          }
        }
      );
    }
  },
  watch: {
    second: {
      handler(newVal) {
        this.num(newVal);
      }
    },
    minute: {
      handler(newVal) {
        this.num(newVal);
      }
    }
  },
  computed: {
    second: function() {
      return this.num(this.seconds);
    },
    minute: function() {
      return this.num(this.minutes);
    }
  }
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
  padding: 0;
}
.box_left {
  float: left;
}
.box_right {
  float: right;
}
//头部
.dark-top {
  width: 100%;
  height: 12.5rem;
  color: #1a1a1a;
  position: relative;
  background-image: url(../../assets/shop/bg_order.png);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  overflow: hidden;
  position: fixed;
  top: 0;
  z-index: 9999;
  .page-back {
    width: 0.5625rem;
    height: 0.9375rem;
    text-decoration: none;
    color: #1a1a1a;
    display: inline-block;
    position: absolute;
    left: 0.9375rem;
    top: 2.4375rem;

    :first-child {
      width: 100%;
      height: 100%;
      background-image: url(../../assets/login/return-white.png);
      background-repeat: no-repeat;
      background-size: contain;
      background-position: center;
      overflow: hidden;
    }
  }
  .top-title {
    text-align: center;
    font-size: 1.125rem;
    color: #fefefe;
    margin-top: 4.75rem;
    // 倒计时
    .topTime {
      margin-top: 0.625rem;
    }
  }
}

//订单信息
.dark-order {
  width: 21.5625rem;
  height: 5.375rem;
  box-shadow: 0 0 0 0.0625rem rgba(0, 0, 0, 0.05);
  position: fixed;
  top: 9.4375rem;
  left: 50%;
  z-index: 9999;
  -ms-transform: translateX(-50%) translateY(0); /* IE 9 */
  -moz-transform: translateX(-50%) translateY(0); /* Firefox */
  -webkit-transform: translateX(-50%) translateY(0); /* Safari 和 Chrome */
  -o-transform: translateX(-50%) translateY(0); /* Opera */
  border-radius: 0.625rem;
  background-color: #ffffffff;
  font-size: 0.875rem;
  color: #333333;
  .dark-order-div1 {
    margin: 1.25rem 0 0 0.9375rem;

    .order-span1 {
      margin-left: 1.9375rem;
    }
  }
  .dark-order-div2 {
    margin: 0.625rem 0 0 0.9375rem;
    .order-span2 {
      margin-left: 1.9375rem;
    }
  }
}
//订单详情列表
.dark-order-list {
  width: 21.5625rem;
  margin: 0 auto;
  .order-list-box {
    width: 21.5625rem;
    height: 10.0625rem;
    border-radius: 0.625rem;
    box-shadow: 0 0 0 0.0625rem rgba(0, 0, 0, 0.05);
    margin-bottom: 0.625rem;
    //商品图
    .order-picture {
      width: 5.625rem;
      height: 8.125rem;
      margin: 0.875rem 0 0 0.875rem;
      background-image: url(../../assets/shop/spimg.png);
      background-repeat: no-repeat;
      background-size: contain;
      background-position: center;
      overflow: hidden;
    }
    //商品内容
    .box_right {
      width: 216px;
      height: 8.125rem;
      margin: 0.875rem 0.875rem 0 0;
      position: relative;
      //标题
      .order-right-contend {
        font-size: 1rem;
        color: #1a1a1a;
      }
      //规格
      .order-right-gauge {
        font-size: 0.75rem;
        color: #999999;
        margin-top: 0.625rem;
      }
      .order-right-price {
        font-size: 1.125rem;
        color: #ff0000;
        position: absolute;
        bottom: 0;
      }
    }
  }
}
/* 底部 */
.dark-foot {
  width: 100%;
  height: 2.8125rem;
  box-shadow: 0.125rem 0.125rem 0.125rem 0.125rem rgba(0, 0, 0, 0.05);
  position: fixed;
  bottom: 0;
  background-color: white;

  .foot-left {
    float: left;

    :first-child {
      margin-top: 0.53125rem;
    }
    p {
      font-size: 0.75rem;
      line-height: 0.9375rem;
      margin-left: 0.9375rem;
    }
    .font-left-color {
      color: rgba(255, 32, 0, 1);
    }
  }
  .foot-button {
    float: right;
    width: 5.625rem;
    height: 1.875rem;
    background-color: rgba(255, 32, 0, 1);
    text-align: center;
    line-height: 1.875rem;
    border-radius: 1.25rem;
    position: relative;
    top: 0.46875rem;
    right: 0.9375rem;
    font-size: 0.9375rem;
    color: rgba(255, 255, 255, 1);
  }
}
</style>
